//
//  HomeViewController.swift
//  MT
//
//  Created by ooops on 2019/7/18.
//  Copyright © 2019年 张强. All rights reserved.
//

import UIKit
import MTCategory
import JXPagingView
import JXCategoryView
import RxSwift
import RxCocoa
import YPNavigationBarTransition

class MTRichClubRateViewController: BaseViewController {
    
    public var listViewDidScrollCallback: ((UIScrollView) -> ())?
    private var listViewDidRefreshCallback: (() -> Void)?
    
    private lazy var provider: MTProvider<MTClubApi> = {
        let provider = MTProvider<MTClubApi>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    let userProvider: MTProvider = MTProvider<UserCenterApi>()
    
    private var result: [MTClubRichListResultModel] = []
    private var currentPage: Int = 1
    private let pageSize: Int = 20
    private var loadType: Int = 1
    private var clubType: Int = 0
    
    
    /// 新建
    /// - Parameters:
    ///   - clubType: 俱乐部类型 - 0 - 最富 / 1 - 最新
    ///   - callback: 刷新完成回调
    convenience init(clubType: Int, callback: (() -> Void)?) {
        self.init()
        self.listViewDidRefreshCallback = callback
        self.clubType = clubType
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "土豪榜"
        view.backgroundColor = UIColor.theme.background
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            //make.left.right.bottom.equalToSuperview()
            //make.top.equalToSuperview().offset(StatusBarHeight + NavigationBarHeight)
        }
        
        setupNavigationBar()
        loadFirst()
    }
    
    override func refreshView() {
        loadFirst()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        tableView.frame = view.bounds
    }
    
    
    // MARK: - 加载数据
    /// - Parameter loadMore: 是否加载更多
    private func loadData(loadMore: Bool) {
        let queryParam: [String : Any] = ["curPage" : currentPage, "pageSize" : pageSize]
        
        if clubType == 0 {
            MTClubTool.queryRich(provider: provider, requestParam: queryParam, complete: { [weak self] (model) in
                
                guard let weakSelf = self else { return }
                weakSelf.comporseData(model: model, loadMore: loadMore)
                
            }) { [weak self] (error) in
                guard let weakSelf = self else { return }
                if !loadMore {
                    weakSelf.listViewDidRefreshCallback?()
                }
            }
        } else {
            MTClubTool.queryLester(provider: provider, requestParam: queryParam, complete: { [weak self] (model) in
                
                guard let weakSelf = self else { return }
                weakSelf.comporseData(model: model, loadMore: loadMore)
                
            }) { [weak self] (error) in
                guard let weakSelf = self else { return }
                if !loadMore {
                    weakSelf.listViewDidRefreshCallback?()
                }
            }
        }
    }
    
    private func comporseData(model: MTClubRichListModel?, loadMore: Bool) {
        weak var weakSelf = self
        weakSelf?.tableView.mj_footer?.endRefreshing()
        weakSelf?.tableView.mj_header?.endRefreshing()
        if weakSelf?.currentPage == 1 {
            weakSelf?.tableView.mj_footer?.state = .idle
        }
        
        if let m = model {
            debugPrint("message: ", m.message ?? "")
            if let r = m.result {
                if (m.page?.pages == weakSelf?.currentPage) {
                    weakSelf?.tableView.mj_footer?.endRefreshingWithNoMoreData()
                }
                if loadMore == true {
                    weakSelf?.result = weakSelf!.result + r
                } else {
                    weakSelf?.result = r
                }
                
                weakSelf?.hiddenHF(isHidden: weakSelf?.result.count == 0)
            } else {
                weakSelf?.hiddenHF(isHidden: true)
            }
            
            DispatchQueue.main.async {
                if !loadMore {
                    weakSelf?.listViewDidRefreshCallback?()
                }
                weakSelf?.tableView.reloadData()
            }
        }
    }
    
    @objc private func hiddenHF(isHidden: Bool) {
        self.tableView.mj_header?.isHidden = isHidden
        self.tableView.mj_footer?.isHidden = isHidden
    }
    
    @objc func loadFirst() {
        self.currentPage = 1
        
        loadData(loadMore: false)
    }
    
    @objc private func loadMore() {
        
        self.currentPage = self.currentPage + 1
        
        loadData(loadMore: true)
        
    }
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: .zero, style: .plain )
        table.delegate = self
        table.dataSource = self
        table.register(MTClubRichListViewCell.self, forCellReuseIdentifier: MTClubRichListViewCell.reuseIdentity())
        table.separatorStyle = .none
        table.tableFooterView = UIView()
        table.backgroundColor = UIColor.theme.background
        table.isScrollEnabled = false
        table.showsVerticalScrollIndicator = false
        table.mj_footer = ViewFactory.normalFooter(target: self, selector: #selector(loadMore))
        table.mj_header = ViewFactory.normalHeader(target: self, selector: #selector(loadFirst))
        table.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: TabBarHeight, right: 0)
        table.emptySetView = ViewFactory.emptySetView { [weak self] in

            guard let weakSelf = self else { return }

            weakSelf.loadFirst()

        }
        return table
    }()
    
    
    private func setupNavigationBar() {
        let item = UIBarButtonItem(customView: createClubBtn)
        navigationItem.rightBarButtonItems = [item]
        
        let leftitem = UIBarButtonItem(customView: mineClubBtn)
        navigationItem.leftBarButtonItems = [leftitem]
    }
    
    lazy var mineClubBtn: UIButton = {
       let btn: UIButton = UIButton(type: .custom)
        btn.setTitle("我的", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(16)
        btn.addTarget(self, action: #selector(mineClub), for: .touchUpInside)
        btn.sizeToFit()
        return btn
    }()
    
    lazy var createClubBtn: UIButton = {
       let btn: UIButton = UIButton(type: .custom)
        btn.setTitle("+ 创建", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(14)
        btn.addTarget(self, action: #selector(queryUserMoney), for: .touchUpInside)
        btn.frame = CGRect(x: 0, y: 0, width: 60, height: 28)
        btn.layer.cornerRadius = 3
        btn.layer.borderColor = UIColor.white.cgColor
        btn.layer.borderWidth = 1
        return btn
    }()
    
    @objc private func mineClub() {
        navigationController?.pushViewController(MTMineClubViewController(), animated: true)
    }
    
    // MARK: - 创建俱乐部
    @objc private func queryUserMoney() {
        /// 查询创建俱乐部所需要消耗的钻石
        MTClubTool.config(provider: provider, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            guard let groupMoney = model?.result?.groupMoney else { return }
            let userMoney = model?.result?.moeny ?? 0
            //let wechatOfficeAccount = model?.result?.wechatOfficeAccount ?? ""
            if model?.code == 200, userMoney < groupMoney {
                //创建专属俱乐部需花费\(groupMoney)钻石您当前余额不够，是否去充值
                UIAlertController.rx.show(in: weakSelf, title: "提示", message: "创建俱乐部需要\(groupMoney)钻石，钻石不足，请充值", buttons: [.cancel("取消"), .default("去充值")]).subscribe(onSuccess: { index in
                    /// 去充值的引导
                    if index == 1 {
                        if UserDefaults.AppValidate.isValidate.storedBool == false {
                            let c = MTPaymentViewController()
                            weakSelf.navigationController?.pushViewController(c, animated: true)
                        } else {
                            let c = MTInAppPurchasesViewController()
                            weakSelf.navigationController?.pushViewController(c, animated: true)
                        }
                    }
                })
                .disposed(by: globalDisposedBag)
            } else {
                /// 跳转去创建俱乐部
                UIAlertController.rx.show(in: weakSelf, title: "提示", message: "创建专属俱乐部需花费\(groupMoney)钻石是否去创建?", buttons: [.cancel("取消"), .default("去创建")]).subscribe(onSuccess: { [weak self] index in
                    guard let weakSelf = self else { return }
                    if index == 1 {
                        let createVC = MTCreateClubViewController { (needRefrence) in
                            /// 创建成功拉取数据
                            weakSelf.loadFirst()
                        }
                        weakSelf.navigationController?.pushViewController(createVC, animated: true)
                    }
                })
                .disposed(by: globalDisposedBag)
            }
        }) { (error) in
            
        }
    }
}

extension MTRichClubRateViewController: WXApiDelegate {
    
    
    
}

extension MTRichClubRateViewController: UITableViewDelegate, UITableViewDataSource {
    
    //MARK: UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.result.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MTClubRichListViewCell.reuseIdentity(), for: indexPath) as! MTClubRichListViewCell
        configureCell(cell: cell, forRowAt: indexPath)
        return cell
    }
    
    func configureCell(cell: MTClubRichListViewCell, forRowAt indexPath: IndexPath) {
        cell.delegate = self
        let model = self.result[indexPath.row]
        model.number = indexPath.row
        if let gid = model.pushId {
            //let conversation = JMSGConversation.groupConversation(withGroupId: "\(gid)")
            //cell.gid = "\(gid)"
            //cell.conversation = conversation
        }
        
        cell.model = model
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.result[indexPath.row]
        //JCChatViewController
        guard let clubName = model.pushId else { return }
        
        JMSGGroup.groupInfo(withGroupId: "\(clubName)", completionHandler: { [weak self] (result, error) in
            guard let weakSelf = self else { return }
            if error == nil, let group = result as? JMSGGroup {
                let clubDetail = MTNewClubDetailViewController(group: group, model: model)
                
                weakSelf.navigationVC?.pushViewController(clubDetail, animated: true)
            }
        })
        
//        JMSGGroup.groupInfo(withGroupId: "\(clubName)", completionHandler: { (result, error) in
//            if error == nil, let group = result as? JMSGGroup {
//                /// 不是这个组的成员
//                group.memberInfoList({ (result, error) in
//                    if error == nil {
//                        if let userInfos: [JMSGGroupMemberInfo] = result as? [JMSGGroupMemberInfo] {
//                            let r : [JMSGUser?] = userInfos.map { (info) -> JMSGUser? in
//                                return info.user
//                            }
//                            /// 判断是否是俱乐部成员
//                            if r.contains(JMSGUser.myInfo()) == false {
//                                MBProgressHUD_JChat.show(text: "请先加入俱乐部", view: self.view)
//                                return
//                            }
//                            /// 创建群聊会话
//                            JMSGConversation.createGroupConversation(withGroupId: "\(clubName)") { [weak self] (conversation, error) in
//                                guard let weakSelf = self else { return }
//
//                                if error == nil, conversation != nil {
//                                    let conv: JMSGConversation = conversation as! JMSGConversation
//                                    weakSelf.navigationController?.pushViewController(JCChatViewController(conversation: conv), animated: true)
//                                }
//                            }
//                        }
//                    }
//                })
//            }
//        })
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
    }
    
}


extension MTRichClubRateViewController: MTClubRichListViewCellDelegate {
    
    func joinClub(cell: MTClubRichListViewCell, model: MTClubRichListResultModel?) {
        
        guard let clubName = model?.pushId else { return }
        
        /// 判断群组类型是否为公开俱乐部
        JMSGGroup.groupInfo(withGroupId: "\(clubName)", completionHandler: { (result, error) in
            if error == nil {
                
//                #if DEBUG
//
//                if let group1: JMSGGroup = result as? JMSGGroup {
//                    if group1.groupType == .private {
//                        MBProgressHUD_JChat.show(text: "此群只能天上有, 凡俗之人不可得", view: self.view)
//                    } else {
//                        MBProgressHUD_JChat.show(text: "尔等尽如此粗鄙", view: self.view)
//                    }
//
//                    if group1.owner == JMSGUser.myInfo().username {
//                        MBProgressHUD_JChat.show(text: "汝之淫威已然荡然此群", view: self.view)
//                    } else {
//                        MBProgressHUD_JChat.show(text: "快快联系群主啊, 里面妹子多", view: self.view)
//                    }
//
//                }
//
//                #endif
                
                /**
                 * 可申请的俱乐部满足的条件
                 *
                 * 如果俱乐部存在
                 * 俱乐部是公开类型
                 * 俱乐部不是自己的
                 */
                guard let group: JMSGGroup = result as? JMSGGroup, group.groupType != .private, group.owner != JMSGUser.myInfo().username else { return }
                
                /// 公开俱乐部
                JMSGGroup.applyJoin(withGid: "\(clubName)", reason: nil) { [weak self] (result, error) in
                    weak var weakSelf = self
                    if error == nil {
                        let currentUser = JMSGUser.myInfo()
                        let info = JCVerificationInfo.create(username: "\(clubName)", nickname: model?.name ?? "", appkey: currentUser.appKey!, resaon: "申请加入俱乐部\(group.name ?? "")", state: JCVerificationType.wait.rawValue, initiator: currentUser.username, type: MTRequestVerifyType.group, eventId: "", clubId: "\(clubName)")
                        
                        JCVerificationInfoDB.shareInstance.insertData(info)
                        NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateVerification), object: nil)
                        MBProgressHUD_JChat.show(text: "加入俱乐部请求已发送", view: weakSelf?.view, 2)
                    } else {
                        if (error! as NSError).code == 856003 {
                            MBProgressHUD_JChat.show(text: "申请已发送, 请耐心等待审核", view: weakSelf?.view)
                        }
                        //MBProgressHUD_JChat.show(text: "\(String.errorAlert(error! as NSError))", view: weakSelf?.view)
                    }
                }
                
            }
        })
    }
    
}

//extension MTRichClubRateViewController: JXPagingViewListViewDelegate {
//    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
//        listViewDidScrollCallback = callback
//    }
//
//
//    func listView() -> UIView {
//        return self.view
//    }
//
//    func listScrollView() -> UIScrollView {
//        return UIScrollView()
//    }
//}

extension MTRichClubRateViewController: JXPagingViewListViewDelegate {
    func listView() -> UIView {
        return view
    }

    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }

    func listScrollView() -> UIScrollView {
        return self.tableView
    }

    func listWillAppear() {
        debugPrint("\(self.title ?? ""):\(#function)")
    }

    func listDidAppear() {
        debugPrint("\(self.title ?? ""):\(#function)")
    }

    func listWillDisappear() {
        debugPrint("\(self.title ?? ""):\(#function)")
    }

    func listDidDisappear() {
        debugPrint("\(self.title ?? ""):\(#function)")
    }
}


extension MTRichClubRateViewController {
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
    }
}
